<?php


namespace app\controller\api;


use app\BaseController;
use app\common\OrderStatus;
use app\models\goods\GoodsModel;
use app\models\goods\GoodsSkuModel;
use app\models\order\OrderEvaluationModel;
use app\services\config\ConfigService;
use app\services\order\OrderService;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;

use app\models\goods\CategoryModel;
use app\models\goods\GoodsCollectModel;

class GoodsController extends BaseController
{

    public function getGoodsLists(){
        try {
            $where = [];
            $keyword = $this->request->param('keyword');
            if ($keyword) {
                $where[] = ['name|intro', 'like', '%' . $keyword . '%'];
            }

            $category_id = $this->request->param('category_id',1);
            if($category_id){
                $list = CategoryModel::where('status', 0)
                    ->field('id,pid,title,img,sort')
                    ->order('pid asc,sort asc')
                    ->select()
                    ->toArray();

                $category_ary = getAllDescendants($list,$category_id);
                if(!empty($category_ary)){
                    $ids = array_column($category_ary,'id');
                    array_push($ids,$category_id);
                    $where[] = ['category_id','in',$ids];
                }else{
                    $where[] = ['category_id','=',$category_id];
                }
            }
            $list = GoodsModel::where('status', 1)->where($where)->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->each(function ($item){
                    $item['sales'] = $item['sales'] + $item['virtual_sales'];
                    $item['goods_sku'] = GoodsSkuModel::where('goods_id',$item['id'])->field('goods_id,name,sell_price,market_price')->order('sort','desc')->select();
                    return $item;
                });
            return $this->success($list);
        }catch (\Exception $exception){
            return $this->error($exception->getMessage());
        }
    }

    public function getPointsMall(){
        try {
            $keywords = $this->request->param('keywords');
            $where = [];
            if($keywords){
                $where[] = ['name','like','%'.$keywords.'%'];
            }
            $where[] = ['is_del','=',0];
            $list = Db::name('pointsmall')->field('id,name,image,integral,original,create_time')->where($where)->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                    ->toArray();
            return $this->success($list);
        }catch (\Exception $exception){
            return $this->error($exception->getMessage());
        }
    }

    public function getGoodsdetails(){
        try {
            $id = $this->request->param('id');
            $goods = GoodsModel::find($id);
            if(!$goods){
                throw new Exception('商品不存在');
            }
            if($goods['status'] != 1){
                throw new Exception('商品已下架');
            }
            $goods['sales'] = $goods['sales'] + $goods['virtual_sales'];
            $goods['purchase_notice'] = ConfigService::getConfigValue('purchase_notice');
            $goods['freight'] = ConfigService::getConfigValue('freight');
            $goods['details'] = GoodsSkuModel::where('goods_id',$goods['id'])->where('is_del',0)->order('sort','desc')->select()->toArray();

            //评论列表
            $evaluationCount = OrderEvaluationModel::where('goods_ids','like','%'.$id.'%')->count();
            $evaluation =  OrderEvaluationModel::where('goods_ids','like','%'.$id.'%')->order('id desc')->find();
            if($evaluation){
                $userinfo = Db::name('user')->where('id',$evaluation['user_id'])->find();

                if($userinfo){
                    $evaluation['nick'] = $userinfo['nick'];
                    $evaluation['avatar'] = $userinfo['avatar'];

                    $pattern = "/^1[3-9]\d{9}$/";
                    if (preg_match($pattern, $userinfo['mobile'])) {
                        // 取出手机号的前三位和后四位
                        $maskedPhoneNumber = substr($userinfo['mobile'], 0, 3) . str_repeat('*', strlen($userinfo['mobile']) - 7) . substr($userinfo['mobile'], -4);
                        $evaluation['mobile'] = $maskedPhoneNumber;
                    } else {
                        $evaluation['mobile'] = $userinfo['mobile'];
                    }
                }else{
                    $evaluation['nick'] = '未知用户';
                    $evaluation['avatar'] = '';
                    $evaluation['mobile'] = '';
                }
                $evaluation['evaluation_time'] = date('Y-m-d',strtotime($evaluation['create_time']));
            }

            $goods['evaluation_count'] = $evaluationCount;
            $goods['evaluation'] = $evaluation;

            return $this->success($goods);
        }catch (\Exception $exception){
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 盲盒列表
     * @return \think\response\Json
     */
    public function getGoodsList()
    {
        try {
            $search = $this->request->param('search', '', 'trim');
            $status = $this->request->param('status', 1, 'int');
            $where = [];
            $userInfo = $this->request->userInfo;
            $paintInfo = Db::name('paint')->where('customer_id', $userInfo['id'])->find();
            if (!$paintInfo) {
                throw new \Exception('请登陆阁主账号');
            }
            $where[] = ['is_appoint', '=', 0];
            if ($status == 1) {
                $where[] = ['status', '=', $status];
            } else {
                $where[] = ['status', '=', 0];
            }

            $where[] = ['paint_id', '=', $paintInfo['id']];
            if ($search) {
                if (isPhoneNumber($search)) {
                    $userIdArr = Db::name('user')->where('mobile', $search)->column('id');
                    $where[] = ['user_id', 'in', $userIdArr];
                } else {
                    $userIdArr = Db::name('user')->where('invite_code', $search)->column('id');
                    $where[] = ['user_id', 'in', $userIdArr];
                }
            }
            $page = $this->page;
            $limit = $this->limit;
            $list = Db::name('goods')
                ->where($where)
                ->order('price', 'desc')
                ->paginate(['list_rows' => $limit, 'page' => $page])
                ->toArray();
            foreach ($list['data'] as &$v) {
                $userInfo = Db::name('user')->where('id', $v['user_id'])->find();
                $v['user_name'] = $userInfo['user_name'] ?? '';
                $v['mobile'] = $userInfo['mobile'] ?? "";
                $v['update_time'] = date('Y-m-d\TH:i:s', $v['update_time']);
                $v['order_status'] = 6;
                $v['price'] = round($v['price']);
            }
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 指派
     * @return \think\response\Json
     */
    public function appoint()
    {
        Db::startTrans();
        try {
            $configInfo = Db::name('config')->where('key', 'appoint_time')->value('value');
            if ($configInfo) {
                $timeArr = explode('-', $configInfo);
                $time1 = $timeArr[0];
                $time2 = $timeArr[1];
                $time = date('H:i');
                if ($time >= $time1 && $time <= $time2) {
                    throw new \Exception('当前时间不能派单');
                }
            }
            $inviteCode = $this->request->param('invite_code', '', 'trim');
            $goodsId = $this->request->param('goods_id', '', 'trim');
            $service = new OrderService();
            $service->appointOrder($inviteCode, $goodsId);
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 拆分
     * @return \think\response\Json
     */
    public function split()
    {
        Db::startTrans();
        try {
            $num = $this->request->param('num', 0, 'int');
            if (!in_array($num, [2, 3])) {
                throw new \Exception('拆分数量错误');
            }
            $goodsId = $this->request->param('goods_id');
//            $orderSn = $this->request->param('order_sn', '', 'trim');
//            $orderInfo = Db::name('order')->where('order_sn', $orderSn)->find();
//            if (!$orderInfo) {
//                throw new \Exception("订单号错误");
//            }
//            if (!in_array($orderInfo['order_status'], [4, 5, 6])) {
//                throw new \Exception("订单处于交易状态不能拆分");
//            }
            $goodsInfo = Db::name('goods')->where('id', $goodsId)->where('status', 1)->find();
            if (!$goodsInfo) {
                throw new \Exception("商品不存在");
            }
            $price = $goodsInfo['price'];
//            if ($price < 6000 && $num == 3) {
//                throw new \Exception('价格不足以拆分3个');
//            }
            $imgArr = Db::name('goods_image')->where('id', '>', 0)->column('img');
            $priceArr = randomSum($price, $num);
            foreach ($priceArr as $k => $v) {
                if ($v == 0) {
                    break;
                }
                // 生成订单
                $newOrderSn = createOrderSn();
                // 购买价格
//                $price = $v;
                // 该订单的上架费
//                $onlinePrice = number_format($price * 0.025, 2);
                // 卖出的价格
//                $payPrice = bcmul($price, 1.04, 2);
//                Db::name('order')->insert([
//                    'paint_id' => $orderInfo['paint_id'],
//                    'user_id' => $orderInfo['user_id'],
//                    'goods_id' => $orderInfo['goods_id'],
//                    'price' => $price,
//                    'online_price' => $onlinePrice,
//                    'pay_price' => $payPrice,
//                    'order_sn' => $newOrderSn,
//                    'old_order_sn' => $orderInfo['old_order_sn'],
//                    'order_status' => $orderInfo['order_status'],
//                    'split_order_sn' => $orderInfo['order_sn'],
//                    'create_time' => date('Y-m-d H:i:s'),
//                    'update_time' => date('Y-m-d H:i:s'),
//                ]);
                shuffle($imgArr);
                if ($k == 0) {
                    $goodsNo = $goodsInfo['goods_no'];
                    $goodsName = $goodsInfo['name'];
                    $code = '';
                } else {
                    $goodsNo = createGoodsCode();
                    $goodsName = preg_replace("/\\d+/", '', $goodsInfo['name']);
                    $code = createGoodsName();
                }
                $data = [
                    'goods_no' => $goodsNo,
                    'paint_id' => $goodsInfo['paint_id'],
                    'name' => $goodsName . $code,
                    'code' => $code,
                    'category' => $goodsInfo['category'],
                    'image' => $goodsInfo['image'],
                    'add_price' => $v,
                    'price' => $v,
                    'user_id' => $goodsInfo['user_id'],
                    'order_sn' => $newOrderSn,
                    'split_goods_id' => $goodsId,
                    'create_time' => time(),
                    'update_time' => time(),
                ];
                Db::name('goods')->insert($data);
            }
            Db::name('goods')->where('id', $goodsId)->update([
                'status' => -1,
                'is_split' => 1,
                'split_time' => date('Y-m-d H:i:s'),
            ]);
//            Db::name('order')->where('order_sn', $orderSn)->update([
//                'is_split' => 1,
//                'split_time' => date('Y-m-d H:i:s'),
//                'update_time' => date('Y-m-d H:i:s'),
//            ]);
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 转场
     * @return \think\response\Json
     */
    public function trans()
    {
        Db::startTrans();
        try {
            $paintNo = $this->request->param('paint_no', '', 'trim');
            if (!$paintNo) {
                throw new \Exception('店铺编号错误');
            }
            $paintInfo = Db::name('paint')->where('paint_code', $paintNo)->find();
            if (!$paintInfo) {
                throw new \Exception('店铺不存在');
            }
//            $orderSn = $this->request->param('order_sn', '', 'trim');
//            $orderInfo = Db::name('order')->where('order_sn', $orderSn)->find();
//            if (!$orderInfo) {
//                throw new \Exception("订单号错误");
//            }
            $goodsId = $this->request->param('goods_id');
            $goodsInfo = Db::name('goods')->where('id', $goodsId)->where('status', 1)->find();
            if (!$goodsInfo) {
                throw new \Exception("商品不存在");
            }
            if ($goodsInfo['paint_id'] == $paintInfo['id']) {
                throw new \Exception("商品已经属于该宝阁");
            }
            Db::name('goods')->where('id', $goodsId)->update([
                'trans_shop' => $paintInfo['id'],
                'trans_time' => date('Y-m-d H:i:s'),
                'trans_status' => 1,
                'update_time' => time()
            ]);

            Db::name('goods_trans')->insert([
                'user_id' => $goodsInfo['user_id'],
                'order_sn' => $goodsInfo['order_sn'],
                'goods_id' => $goodsId,
                'paint_id' => $goodsInfo['paint_id'],
                'trans_paint_id' => $paintInfo['id'],
                'name' => $goodsInfo['name'],
                'price' => $goodsInfo['price'],
                'type' => 0,
                'create_time' => time(),
                'update_time' => time(),
            ]);
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 封存
     * @return \think\response\Json
     */
    public function del()
    {
        Db::startTrans();
        try {
            $reason = $this->request->param('reason', '', 'trim');
            if (!$reason) {
                throw new \Exception('请输入封存原因');
            }
//            $orderSn = $this->request->param('order_sn', '', 'trim');
//            $orderInfo = Db::name('order')->where('order_sn', $orderSn)->find();
//            if (!$orderInfo) {
//                throw new \Exception("订单号错误");
//            }
            $goodsId = $this->request->param('goods_id');
            $goodsInfo = Db::name('goods')->where('id', $goodsId)->where('status', 1)->find();
            if (!$goodsInfo) {
                throw new \Exception("商品不存在");
            }
//            Db::name('order')->where('order_sn', $orderSn)->update([
//                'is_del' => 1,
//                'update_time' => time()
//            ]);
            Db::name('goods')->where('id', $goodsId)->update([
                'status' => 0,
                'update_time' => time()
            ]);
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 解封
     * @return \think\response\Json
     */
    public function up()
    {
        Db::startTrans();
        try {
            $goodsId = $this->request->param('goods_id');
            $goodsInfo = Db::name('goods')->where('id', $goodsId)->find();
            if (!$goodsInfo) {
                throw new \Exception("红木不存在");
            }
            if ($goodsInfo['status'] != 0) {
                throw new \Exception("红木不是封存状态");
            }
            Db::name('goods')->where('id', $goodsId)->update([
                'status' => 1,
                'update_time' => time()
            ]);
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 上架
     * @return \think\response\Json
     */
    public function online()
    {
        Db::startTrans();
        try {
            $status = $this->request->param('status', '', 'int');
            if ($status == '') {
                throw new \Exception('状态错误');
            }
            $id = $this->request->param('id', '', 'trim');
            $orderInfo = Db::name('goods_trans')->where('id', $id)->find();
            if (!$orderInfo) {
                throw new \Exception("订单不存在");
            }
            Db::name('goods_trans')->where('id', $id)->update([
                'status' => $status,
                'update_time' => time()
            ]);
            Db::name('goods')->where('id', $orderInfo['goods_id'])->update([
                'paint_id' => $orderInfo['trans_paint_id'],
                'update_time' => time()
            ]);
            Db::commit();
            return $this->success();
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 商品收藏
     * @return \think\response\Json
     */
    public function collect()
    {
        Db::startTrans();
        try {
            $goods_id = $this->request->param('goods_id', '', 'trim');
            $user_id = $this->request->userId;
            $collectInfo = Db::name('goods_collect')->where('goods_id', $goods_id)->where('user_id',$user_id)->find();
            if ($collectInfo) {
                //删除收藏
                Db::name('goods_collect')->where('id',$collectInfo['id'])->delete();
                $collect = 0;
            }else{
                //添加收藏
                Db::name('goods_collect')->insert([
                    'user_id' => $user_id,
                    'goods_id' => $goods_id,
                    'create_time' => time(),
                    'update_time' => time(),
                ]);
                $collect = 1;
            }
            Db::commit();
            return $this->success(['collect' => $collect]);
        } catch (\Exception $exception) {
            Db::rollback();
            return $this->error($exception->getMessage());
        }
    }


    /**
     * 收藏列表
     * @return \think\response\Json
     */
    public function getCollectList()
    {
        try {
            $userId = $this->request->userId;
            $list = GoodsCollectModel::where('user_id', $userId)
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->toArray();
            foreach ($list['data'] as &$v) {
                $techInfo = Db::name('goods')->where('id', $v['goods_id'])->find();
                $v['goods_name'] = $techInfo['name'] ?? '';
                $v['goods_price'] = $techInfo['sell_price'] ?? '';
                $v['goods_image'] = $techInfo['image'] ?? '';
                $v['sales'] = $techInfo['sales'] ?? '';
                $v['sales'] = $techInfo['sales'] ? $techInfo['sales'] + $techInfo['virtual_sales'] : '';
                $v['green_scores'] = $techInfo['green_scores'] ?? '';
            }
            return $this->success($list);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 商品评论列表
     * @return void
     */
    public function evaluationList()
    {
        try {
            $userId = $this->request->userId;
            $goods_id = $this->request->param('goods_id');
            $type = $this->request->param('type','');


            // 获取当前时间，并计算最近7天的日期
            $now = time();
            $lastDays = $now - (7 * 24 * 3600); // 7天*24小时*3600秒

            $where = [];
            if($type == 1){
                $where[] = ['create_time','>=',$lastDays];
            }

            $lastDaysCount = OrderEvaluationModel::where('goods_ids','like','%'.$goods_id.'%')->where('create_time','>=',$lastDays)->count();
            $evaluationCount = OrderEvaluationModel::where('goods_ids','like','%'.$goods_id.'%')->where($where)->count();
            $evaluation =  OrderEvaluationModel::where('goods_ids','like','%'.$goods_id.'%')->where($where)
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->order('id desc')
                ->toArray();


            $user_ids = array_column($evaluation['data'],'user_id');
            $user_data = Db::name('user')->where('id','in',$user_ids)->column('id,nick,avatar,mobile','id');

            foreach($evaluation['data'] as &$item){
                if(isset($user_data[$item['user_id']])){
                    $item['nick'] = $user_data[$item['user_id']]['nick'];
                    $item['avatar'] = $user_data[$item['user_id']]['avatar'];

                    $pattern = "/^1[3-9]\d{9}$/";
                    if (preg_match($pattern, $user_data[$item['user_id']]['mobile'])) {
                        // 取出手机号的前三位和后四位
                        $maskedPhoneNumber = substr($user_data[$item['user_id']]['mobile'], 0, 3) . str_repeat('*', strlen($user_data[$item['user_id']]['mobile']) - 7) . substr($user_data[$item['user_id']]['mobile'], -4);
                        $item['mobile'] = $maskedPhoneNumber;
                    } else {
                        $item['mobile'] = $user_data[$item['user_id']]['mobile'];
                    }
                }else{
                    $item['nick'] = '隐藏用户';
                    $item['avatar'] = '';
                    $item['mobile'] = '隐藏用户';
                }
                $item['evaluation_time'] = date('Y-m-d',strtotime($item['create_time']));
            }

            $data = ['lastDaysCount' => $lastDaysCount,'total' => $evaluationCount,'data' => $evaluation];

            return $this->success($data);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 店铺商品列表
     * @return \think\response\Json
     */
    public function getShopGoodsLists(){
        try {
            $where = [];
            $shop_id = $this->request->param('shop_id');
            $keyword = $this->request->param('keyword');
            if ($keyword) {
                $where[] = ['name|intro', 'like', '%' . $keyword . '%'];
            }
            if($shop_id){
                $where[] = ['shop_id','=',$shop_id];

                $shopinfo = Db::name('shop')->where('id',$shop_id)->field('shop_name,img,logo')->find();
            }else{
                $shop_name = ConfigService::getConfigValue('shop_name');
                $shop_img = ConfigService::getConfigValue('shop_img');
                $shop_logo = ConfigService::getConfigValue('shop_logo');

                $shopinfo = ['shop_name' => $shop_name,'img' => $shop_img,'logo' => $shop_logo];
            }

            $list = GoodsModel::where('status', 1)
                ->where($where)
                ->paginate(['list_rows' => $this->limit, 'page' => $this->page])
                ->each(function ($item){
                    $item['goods_sku'] = GoodsSkuModel::where('goods_id',$item['id'])
                        ->field('goods_id,name,sell_price,market_price')
                        ->order('sort','desc')
                        ->select();
                    return $item;
                });
            $data = ['shop' => $shopinfo,'goods' => $list];
            return $this->success($data);
        }catch (\Exception $exception){
            return $this->error($exception->getMessage());
        }
    }

}